#include <stdlib.h>
#include <string.h>
#include "headers.h"
#include "bounded_string.h"

#define ARRAY_SIZE(x) (sizeof (x) / sizeof (*x))

static BOUNDED_STRING message_headers[] = {
	{"Authorization", 13},
	{"Connection", 10},
	{"Content-Length", 14},
	{"Content-Type", 12},
	{"Host", 4},
	{"If-Modified-Since", 17},
	{"Keep-Alive", 10},
	{"Proxy-Connection", 16},
	{"Range", 5},
	{"Server", 6},
	{"Transfer-Encoding", 17},
	{"User-Agent", 10}
};

eMessageHeader get_header (const char *string, size_t len)
{
	int i, j, pivot;
	int ret;

	i = 0;
	j = ARRAY_SIZE (message_headers) - 1;

	while (i <= j) {
		pivot = (i + j) / 2;
		ret = strncasecmp (string, message_headers[pivot].string, len);
		if (ret < 0) {
			j = pivot - 1;
		} else if (ret == 0) {
			if (len < message_headers[pivot].len) {
				j = pivot - 1;
			} else if (len == message_headers[pivot].len) {
				return (eMessageHeader) pivot;
			} else {
				i = pivot + 1;
			}
		} else {
			i = pivot + 1;
		}
	}

	return UNKNOWN_HEADER;
}
